<?php
namespace App\HttpController\Common;

use App\Utility\Traits\JsonReturn;
use EasySwoole\Core\Http\AbstractInterface\REST;
use EasySwoole\Core\Utility\File;
use \EasySwoole\Core\Http\Request;

class Upload extends Rest
{
    use JsonReturn;
    /**
     * 上传图片 二进制流
     */
    public function POSTIndex()
    {
        $data = $this->request()->getBody()->__toString();
        $dir = EASYSWOOLE_ROOT . '/Public';
        $date = date('Ymd');
        $filePath = '/uploads/' . $date . '/' . md5($date . time()) . ".jpg";
        File::createDir($dir . '/uploads/' . $date);
        $fullPath = $dir . $filePath;
        $file = fopen($fullPath, "w"); //打开文件准备写入
        fwrite($file, $data); //写入
        fclose($file); //关闭
        $this->json(['data' => $filePath]);
    }

    /**
     * base64格式图片
     *
     * @return void
     */
    public function POSTBase64()
    {
        $base64_image_content = $this->request()->getBody()->__toString();
        $dir = EASYSWOOLE_ROOT . '/Public';
        $img = base64_decode($data);
        $date = date('Ymd');
        $filePath = '/uploads/' . $date . '/' . md5($date . time()) . ".jpg";
        File::createDir($dir . '/uploads/' . $date);
        $fullPath = $dir . $filePath;
        $file = fopen($fullPath, "w"); //打开文件准备写入
        fwrite($file, $base64_image_content); //写入
        fclose($file); //关闭
        $this->json(['data' => $filePath]);
    }
}